<?php
namespace frontend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\web\IdentityInterface;


class Posts extends ActiveRecord
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    const STATUS = 3;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%posts}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'describe'], 'trim'],
            [['title'], 'required','message' => '{attribute}不能为空'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'title' => '标题',
            //'describe' => '内容',
//            'set_posts_id' => '发帖人id',
//            'set_posts_name' => '发帖人',
        ];
    }

    public function scenarios()
    {
        return [
            'default' => [
                'title',
                'describe',
                'sort',
                'banner',
                'video',
            ],
            'create' => [
                'id',
                'title',
                'describe',
                'img',
                'set_posts_id',
                'set_posts_name',
                'status',
                'create_time',
                'update_time',
            ],
            'update' => [
                '!id',
                'title',
                'describe',
                'img',
                'sort',
                'banner',
                'video',
                'admin_id',
                'admin_name'.
                'status',
                'create_time',
                'update_time',
                'deleted_at',
            ],
            'delete' => [
                '!id',
                'deleted_at',
            ],
        ];
    }

    public static function addNum($id){
        $model = static::findOne(['id' => $id]);
        $res = $model->toArray();
        $model->comment_num = $res['comment_num'] + 1;
        return $model->save();
        //$res = $model->updateCounters(['comment_num' => 1],['id' => $id]);
        //$res = $model->updateAllCounters(['comment_num' => 1],['id' => $id]);
        //$res = $model->updateAll(['comment_num' => ['comment_num' => 1]],['id' => $id]);
        return $res;
    }

    public static function deleteMyPosts($data){
        $model = static::findOne(['id' => $data['id'],'set_posts_id' => $data['set_posts_id']]);
        if(empty($model)){
            return false;
        }
        $model->scenario = 'delete';
        $model->deleted_at = time();
        return $model->save();
    }

    /**
     * 更新数据
     * @author hey_heyang(635870453@qq.com)
     */
    public static function saveInfo($scenario, $data, $id = 0){
        if (!in_array($scenario, ['create', 'update'])) {
            return false;
        }
        $t = static::getDb()->beginTransaction();
        try {
            if ($scenario == 'update') {
                $id = intval($id);
                if (!$id) {
                    return false;
                }
                $model           = static::findOne(['id' =>$id]);
                if(empty($model)) throw new \Exception('不存在此用户');
                $model->scenario = 'update';
            } else {
                $model           = new self();
                $model->scenario = 'create';
            }
            $model->setAttributes($data, false);
            if (!$model->save()) {
                $t->rollBack();
                return $model;
            }
            $model->refresh();
            $t->commit();
            return $model->attributes['id'];
            //return $model;
        } catch (\Exception $e) {
            $t->rollback();
            return array('error'=>'操作失败');
        }
    }

    /**
     * @inheritdoc
     */
    public static function selectFieldData($field)
    {
        $query = new \yii\db\Query();
        $query->select($field)->from('posts');
        $query->where(['deleted_at' => null]);
        $query->orderBy([
            'created_at' => SORT_DESC,
        ]);

        $command = $query->createCommand();
        $result = $command->queryAll();
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function selectInfo($data = [])
    {
        $query = new \yii\db\Query();
        $query->select(['*'])->from('posts');
        $query->where(['deleted_at' => null]);
        $query->andWhere(['posts.status' => self::STATUS]);
        $query->orderBy([
            'created_at' => SORT_DESC,
        ]);
        if(!empty($data['status'])){
            $query->andWhere(['status' => $data['status']]);
        }
        if(!empty($data['start_date']) && !empty($data['end_date'])){
            $query->andFilterWhere(['between','created_at',$data['start_date'], $data['end_date']]);
        }
        $command = $query->createCommand();
        $result = $command->queryAll();
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function selectData($data = [],$field = '*')
    {

        $model = new \frontend\models\Comment();
        $collect = new \frontend\models\PostsCollect();
        $group_member = new \frontend\models\GroupMember();
        $group = new \frontend\models\Group();
        $posts = new \frontend\models\PostsJoin();
        $query = new \yii\db\Query();
        $query->select([$field])->from('posts');
        $query->leftJoin('posts_join j','`posts`.`id` = `j`.`posts_id`');
        $query->leftJoin('member m','`posts`.`set_posts_id` = `m`.`id`');
        $query->where(['posts.deleted_at' => null]);
        $query->andWhere(['j.deleted_at' => null]);
        $query->andWhere(['posts.status' => self::STATUS]);

        $query->orderBy([
            'posts.created_at' => SORT_DESC,
        ]);
        if(!empty($data['movie_id'])){
            $query->andWhere(['movie_id' => $data['movie_id']]);
        }
        if(!empty($data['group_id'])){
            $query->andWhere(['group_id' => $data['group_id']]);
        }
        if(!empty($data['data'])){
            $query->andWhere(['like','title',$data['data']]);
        }
        if(!empty($data['set_posts_id'])){
            $query->andWhere(['set_posts_id' => $data['set_posts_id']]);
        }
        if(!empty($data['for_group'])){
            $query->andWhere(['not',['j.group_id' => null]]);
        }
        if(!empty($data['limit'])){
            $query->limit($data['limit']);
        }
        $command = $query->createCommand();
        $result = $command->queryAll();
        foreach ($result as $k => $v){
            if(!empty($data['auth'])){
                $rat = $posts::findOne(['posts_id' => $v['id']]);
                $rap = $group_member::findOne(['group_id' => $rat['group_id'],'member_id' => $data['member_id']]);
                $result[$k]['auth'] = empty($rap)?'no':'yes';
            }
            if(!empty($data['get_group'])){
                $rat = $posts::findOne(['posts_id' => $v['id']]);
                $rap = $group::findOne(['id' => $rat['group_id']]);
                $result[$k]['group_id'] = $rap['id'];
                $result[$k]['group_name'] = $rap['name'];
            }
            $result[$k]['comment_num'] = count($model::selectInfo(['posts_id' => $v['id']],'id'));
            if(!empty($data['my_posts']) && $data['my_posts'] == 1){
                $result[$k]['created_at'] = date('Y-m-d',$v['created_at']);
                $result[$k]['like_num'] = count($collect::selectData(['posts_id' => $v['id'],'is_like' => 1],'id'));
                $result[$k]['collect_num'] = count($collect::selectData(['posts_id' => $v['id'],'is_collect' => 1],'id'));
                if(!empty($data['member_id'])){
                    $like = $collect::findOneData(['posts_id' => $v['id'],'member_id' => $data['member_id']],'is_like');
                    if(!empty($like)){
                        if($like['is_like'] == 1){
                            $result[$k]['is_like'] = 1;
                        }else{
                            $result[$k]['is_like'] = 2;
                        }
                    }else{
                        $result[$k]['is_like'] = 2;
                    }

                    $isCollect = $collect::findOneData(['posts_id' => $v['id'],'member_id' => $data['member_id']],'is_collect');
                    if(!empty($isCollect)){
                        if($isCollect['is_collect'] == 1){
                            $result[$k]['is_collect'] = 1;
                        }else{
                            $result[$k]['is_collect'] = 2;
                        }
                    }else{
                        $result[$k]['is_collect'] = 2;
                    }

                }else{
                    $result[$k]['is_like'] = 2;
                    $result[$k]['is_collect'] = 2;
                }


                $result[$k]['img'] = explode(",",$v['img']);
            }
        }
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function mySelectData($data = [],$field = '*')
    {
        $model = new \frontend\models\Comment();
        $collect = new \frontend\models\PostsCollect();
        $query = new \yii\db\Query();
        $query->select([$field])->from('posts');
        $query->leftJoin('posts_join j','`posts`.`id` = `j`.`posts_id`');
        $query->leftJoin('member m','`posts`.`set_posts_id` = `m`.`id`');
        $query->where(['posts.deleted_at' => null]);
        //$query->andWhere(['posts.status' => self::STATUS]);
        $query->orderBy([
            'posts.created_at' => SORT_DESC,
        ]);
        if(!empty($data['movie_id'])){
            $query->andWhere(['movie_id' => $data['movie_id']]);
        }
        if(!empty($data['group_id'])){
            $query->andWhere(['group_id' => $data['group_id']]);
        }
        if(!empty($data['data'])){
            $query->andWhere(['like','title',$data['data']]);
        }
        if(!empty($data['set_posts_id'])){
            $query->andWhere(['set_posts_id' => $data['set_posts_id']]);
        }
        if(!empty($data['limit'])){
            $query->limit($data['limit']);
        }
        $command = $query->createCommand();
        $result = $command->queryAll();
        foreach ($result as $k => $v){
            $result[$k]['comment_num'] = count($model::selectInfo(['posts_id' => $v['id']],'id'));
            if(!empty($data['my_posts']) && $data['my_posts'] == 1){
                $result[$k]['created_at'] = date('Y-m-d',$v['created_at']);
                $result[$k]['like_num'] = count($collect::selectData(['posts_id' => $v['id'],'is_like' => 1],'id'));
                $result[$k]['collect_num'] = count($collect::selectData(['posts_id' => $v['id'],'is_collect' => 1],'id'));
                $like = $collect::findOneData(['posts_id' => $v['id'],'member_id' => $v['set_posts_id']],'is_like');
                if(!empty($like)){
                    if($like['is_like'] == 1){
                        $result[$k]['is_like'] = 1;
                    }else{
                        $result[$k]['is_like'] = 2;
                    }
                }else{
                    $result[$k]['is_like'] = 2;
                }
                $isCollect = $collect::findOneData(['posts_id' => $v['id'],'member_id' => $v['set_posts_id']],'is_collect');
                if(!empty($isCollect)){
                    if($isCollect['is_collect'] == 1){
                        $result[$k]['is_collect'] = 1;
                    }else{
                        $result[$k]['is_collect'] = 2;
                    }
                }else{
                    $result[$k]['is_collect'] = 2;
                }
                $result[$k]['img'] = explode(",",$v['img']);
            }
        }
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function findOneData($id,$field = '*',$memberId)
    {
        $model = new \frontend\models\PostsCollect();
        $comment = new \frontend\models\Comment();
        $query = new \yii\db\Query();
        $query->select([$field])->from('posts');
        $query->leftJoin('member m','`posts`.`set_posts_id` = `m`.`id`');
        $query->where(['`posts`.`deleted_at`' => null]);
        //$query->andWhere(['posts.status' => self::STATUS]);
        $query->andWhere(['`posts`.`id`' => $id]);
        $query->andWhere(['posts.status' => self::STATUS]);
        $command = $query->createCommand();
        $result = $command->queryOne();
        if(!empty($result['created_at']))
            $result['created_at'] = date('m-d H:i:s',$result['created_at']);
        $result['collect_num'] = count($model::selectData(['posts_id' => $id,'is_collect' => 1],'`id`'));
        $result['like_num'] = count($model::selectData(['posts_id' => $id,'is_like' => 1],'`id`'));
        $result['comment_num'] = count($comment::selectInfo(['posts_id' => $id],'id'));
        //$result['comment_list'] = $comment::findAllData(['posts_id' => $id],'`m`.`username`,`m`.`head_img`,`comment`.`comment`,`comment`.`created_at`');
        $like = $model::findOneData(['posts_id' => $result['id'],'member_id' => $memberId],'is_like');
        if(!empty($like)){
            if($like['is_like'] == 1){
                $result['is_like'] = 1;
            }else{
                $result['is_like'] = 2;
            }
        }else{
            $result['is_like'] = 2;
        }
        $collect = $model::findOneData(['posts_id' => $result['id'],'member_id' => $memberId],'is_collect');
        if(!empty($collect)){
            if($collect['is_collect'] == 1){
                $result['is_collect'] = 1;
            }else{
                $result['is_collect'] = 2;
            }
        }else{
            $result['is_collect'] = 2;
        }
        $result['img'] = explode(",",$result['img']);
        //var_dump($query->createCommand()->getRawSql());exit;
        return $result;
    }


    /**
     * 获取热门讨论信息
     * @author hey_heyang(635870453@qq.com)
     * @return json
     */
    public  function  getHotComment(){
        $condition = ['posts.deleted_at'=>null,'posts.status'=>3,'is_like'=>1];
        $list = (new Query())
            ->select('count(1) as num,posts.id as posts_id')
            ->from('posts')
            ->innerJoin('posts_collect','posts_collect.posts_id=posts.id')
            ->where($condition)
            ->groupBy('posts.id')
            ->orderBy('num DESC,posts_id DESC')
            ->all();
        if(count($list)){
            foreach($list as $key=>$value){
                $data_info[$key] = $this->find()->innerJoin('member','member.id=posts.set_posts_id')->select('posts.id,posts.title,member.head_img')->where(['posts.id'=>$value['posts_id']])->asArray()->one();
                if(empty($data_info[$key])){
                    unset($data_info[$key]);
                }
                if(count($data_info)==3) break;
            }

        }
        return empty($data_info)?array():array_values($data_info);


    }

}
